package com.genexususa.eo.bing.data.results;

import com.genexususa.eo.bing.CampaignManagementServiceClasses.BatchError;
import com.genexususa.eo.bing.CampaignManagementServiceClasses.GoalError;
import com.genexususa.eo.bing.CampaignManagementServiceClasses.GoalResult;
import com.genexususa.eo.bing.CampaignManagementServiceClasses.Step;
import com.genexususa.eo.bing.data.wsSubclasses.GxGoal;
import com.genexususa.eo.bing.data.wsSubclasses.GxStep;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "GoalResult")
public class GxGoalResult extends GxGeneralResult {
    @XmlElement(name = "GxGoalId")
    public long gxGoalId;
    @XmlElement(name = "BingGoalId")
    public long bingGoalId;
    @XmlElementWrapper(name = "StepResultCollection")
    @XmlElement(name = "StepResult")
    public GxIdResult[] stepResults;

    public GxGoalResult() {
        super();
    }

    public GxGoalResult(GxGoal gxGoal) {
        super();
        this.gxGoalId = gxGoal.getGxId();
        Step[] gxSteps = gxGoal.getSteps();
        if (gxSteps != null) {
            this.stepResults = new GxIdResult[gxSteps.length];
            for (int i=0; i<gxSteps.length; i++) {
                this.stepResults[i] = new GxIdResult(((GxStep)gxSteps[i]).getGxId());
            }
        }
    }

    public GxGoalResult(GxGoal gxGoal, GoalResult goalResult) {
        super();
        this.gxGoalId = gxGoal.getGxId();
        this.bingGoalId = goalResult.getGoalId();
        Step[] gxSteps = gxGoal.getSteps();
        long[] bingStepsIds = goalResult.getStepIds();
        if (gxSteps != null && bingStepsIds != null) {
            this.stepResults = new GxIdResult[gxSteps.length];
            for (int i=0; i<gxSteps.length || i<bingStepsIds.length; i++) {
                if (i >= bingStepsIds.length) {
                    this.stepResults[i] = new GxIdResult(((GxStep)gxSteps[i]).getGxId());
                } else if (i >= gxSteps.length) {
                    this.stepResults[i] = new GxIdResult(0, bingStepsIds[i]);
                } else {
                    this.stepResults[i] = new GxIdResult(((GxStep)gxSteps[i]).getGxId(), bingStepsIds[i]);
                }
            }
        }
    }

    public void addGoalError(GoalError error) {
        this.hasError = true;
        BatchError[] batchErrors = error.getBatchErrors();
        for (int i=0; i<batchErrors.length; i++) {
            this.addBatchError(batchErrors[i]);
        }
        batchErrors = error.getStepErrors();
        for (int i=0; i<batchErrors.length; i++) {
            this.addStepError(batchErrors[i]);
        }
    }

    public void addStepError(BatchError error) {
        this.stepResults[error.getIndex()].addBatchError(error);
    }
}
